<template>
	<view class="salary-container">
		<!-- 顶部装饰元素 -->
		<view class="decoration-top">
			<view class="circle pink"></view>
			<view class="circle blue"></view>
			<view class="circle yellow"></view>
		</view>

		<!-- 主内容区域 -->
		<view class="content">
			<!-- 工资概览卡片 -->
			<view class="salary-card animate__animated animate__fadeInDown">
				<view class="salary-header">
					<text class="month">{{currentMonth}}月工资</text>
					<text class="amount">¥{{totalSalary.toFixed(2)}}</text>
				</view>

				<!-- 收入来源图表 -->
				<view class="income-chart">
					<view class="chart-bar checkin" :style="{width: `${(checkinSalary/totalSalary)*100}%`}">
						<text class="chart-label">打卡收入</text>
						<text class="chart-value">{{checkinSalary.toFixed(2)}}元</text>
					</view>
					<view class="chart-bar appointment" :style="{width: `${(appointmentSalary/totalSalary)*100}%`}">
						<text class="chart-label">预约收入</text>
						<text class="chart-value">{{appointmentSalary.toFixed(2)}}元</text>
					</view>
				</view>
			</view>

			<!-- 打卡收入部分 -->
			<view class="detail-section checkin animate__animated animate__fadeInUp" style="animation-delay: 0.1s">
				<view class="section-header">
					<image class="section-icon" src="/static/icons/checkin.png"></image>
					<text class="section-title">打卡收入</text>
					<text class="section-total">+{{checkinSalary.toFixed(2)}}元</text>
				</view>

				<view class="checkin-list">
					<view class="checkin-item" v-for="(item, index) in sortedCheckinData" :key="'checkin-'+index"
						@click="showCheckinDetail(item)">
						<view class="date-badge">
							<text class="day">{{formatFullDate(item.date)}}</text>
							<text class="week">星期{{formatWeek(item.date)}}</text>
						</view>
						<view class="info">
							<text class="time">{{formatTime(item.checkInTime)}} -
								{{item.checkOutTime ? formatTime(item.checkOutTime) : '未打卡'}}</text>
							<view class="status-badge"
								:class="item.checkOutTime ? (getWorkDuration(item) === 1 ? 'completed' : 'partial') : 'partial'">
								{{item.checkOutTime ? (getWorkDuration(item) === 1 ? '全天' : '半天') : '未完成'}}
							</view>
						</view>
						<view class="amount-badge">+{{calculateDailySalary(item)}}元</view>
					</view>
				</view>
			</view>

			<!-- 预约收入部分 -->
			<view class="detail-section appointment animate__animated animate__fadeInUp" style="animation-delay: 0.2s">
				<view class="section-header">
					<image class="section-icon" src="/static/icons/appointment.png"></image>
					<text class="section-title">预约收入</text>
					<text class="section-total">+{{appointmentSalary.toFixed(2)}}元</text>
				</view>

				<view class="appointment-list">
					<view class="appointment-item" v-for="(item, index) in appointmentData" :key="'appointment-'+index"
						@click="showAppointmentDetail(item)">
						<image class="avatar" src='/static/aver1.jpg'></image>
						<view class="info">
							<text class="name">{{item.studentName}}</text>
							<text class="course">{{item.appointmentContent}} ·
								{{parseDuration(item.appointmentTime)}}分钟</text>
							<text class="time">{{formatAppointmentTime(item.appointmentTime)}}</text>
						</view>
						<view class="amount-badge">+{{item.money}}元</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部统计 -->
		<view class="footer-stats animate__animated animate__fadeInUp" style="animation-delay: 0.3s">
			<view class="stat-item">
				<text class="stat-value">{{validCheckinDays}}</text>
				<text class="stat-label">打卡天数</text>
			</view>
			<view class="stat-divider"></view>
			<view class="stat-item">
				<text class="stat-value">{{appointmentData.length}}</text>
				<text class="stat-label">预约次数</text>
			</view>
			<view class="stat-divider"></view>
			<view class="stat-item">
				<text class="stat-value">{{totalSalary.toFixed(2)}}</text>
				<text class="stat-label">总收入</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				teacher: {},
				currentMonth: new Date().getMonth() + 1,
				teacherId: null,
				checkinData: [],
				appointmentData: [],
				checkinSalary: 0,
				appointmentSalary: 0,
				totalSalary: 0,
			}
		},
		computed: {
			validCheckinDays() {
				return this.checkinData.filter(item => item.checkInTime).length;
			},
			sortedCheckinData() {
				// 按日期从近到远排序
				return [...this.checkinData].sort((a, b) => {
					return new Date(b.date) - new Date(a.date);
				});
			}
		},
		methods: {
			// 计算工作时段（1表示全天，0.5表示半天）
			getWorkDuration(item) {
				if (!item.checkInTime || !item.checkOutTime) return 0;

				const checkInHour = this.getHourFromTime(item.checkInTime);
				const checkOutHour = this.getHourFromTime(item.checkOutTime);

				// 上午签到且下午5点后签退算全天
				if (checkInHour < 12 && checkOutHour >= 17) {
					return 1; // 全天
				}
				// 上午签到且11点-下午5点之间签退算半天
				else if (checkInHour < 12 && checkOutHour >= 11 && checkOutHour < 17) {
					return 0.5; // 半天
				}
				// 其他情况默认算半天
				return 0.5;
			},

			// 从时间字符串中提取小时
			getHourFromTime(timeStr) {
				if (!timeStr) return 0;
				const timePart = timeStr.includes(' ') ? timeStr.split(' ')[1] : timeStr;
				return parseInt(timePart.split(':')[0]);
			},

			// 计算单日工资
			calculateDailySalary(item) {
				if (!item.checkInTime) return 0;
				if (!item.checkOutTime) return 0;

				const duration = this.getWorkDuration(item);
				return (this.teacher.money * duration).toFixed(2);
			},

			// 格式化完整日期显示 (如: 7月10日)
			formatFullDate(dateStr) {
				const date = new Date(dateStr);
				return `${date.getMonth() + 1}月${date.getDate()}日`;
			},

			// 格式化星期显示
			formatWeek(dateStr) {
				const weeks = ['日', '一', '二', '三', '四', '五', '六'];
				const date = new Date(dateStr);
				return weeks[date.getDay()];
			},

			// 格式化时间显示 (如: 08:30)
			formatTime(timeStr) {
				if (!timeStr) return '';
				const timePart = timeStr.includes(' ') ? timeStr.split(' ')[1] : timeStr;
				return timePart.substring(0, 5);
			},

			// 解析预约时长
			parseDuration(appointmentTime) {
				const match = appointmentTime.match(/(\d+)分钟/);
				return match ? match[1] : '0';
			},

			// 格式化预约时间
			formatAppointmentTime(appointmentTime) {
				return appointmentTime.replace('分钟', 'min');
			},

			// 显示打卡详情
			showCheckinDetail(item) {
				let message = '';
				if (item.checkInTime && item.checkOutTime) {
					const duration = this.getWorkDuration(item);
					message =
						`上班时间: ${this.formatTime(item.checkInTime)}\n下班时间: ${this.formatTime(item.checkOutTime)}\n工作时长: ${duration === 1 ? '全天' : '半天'}\n当日收入: ${this.calculateDailySalary(item)}元`;
				} else if (item.checkInTime) {
					message = `上班时间: ${this.formatTime(item.checkInTime)}\n下班时间: 未打卡\n当日收入: 0元`;
				} else {
					message = '当日未打卡';
				}

				uni.showModal({
					title: `${this.formatFullDate(item.date)} 打卡详情`,
					content: message,
					showCancel: false,
					confirmText: '知道了'
				});
			},

			// 显示预约详情
			showAppointmentDetail(item) {
				uni.showModal({
					title: `${item.studentName}的预约`,
					content: `课程: ${item.appointmentContent}\n时长: ${this.parseDuration(item.appointmentTime)}分钟\n收入: ${item.money}元`,
					showCancel: false,
					confirmText: '知道了'
				});
			},

			// 获取教师ID
			getTeacherId() {
				return new Promise((resolve) => {
					uni.getStorage({
						key: 'teacher',
						success: (res) => {
							this.teacher = res.data;
							this.teacherId = res.data.teacherId;
							resolve(res.data.teacherId);
						},
						fail: () => {
							uni.showToast({
								title: '获取教师信息失败',
								icon: 'none'
							});
							resolve(null);
						}
					});
				});
			},

			// 获取打卡数据
			async getCheckinData() {
				try {
					const res = await uni.request({
						url: `${globalVariable}/getAllTeacherCheck?teacherId=${this.teacherId}`
					});

					if (res.data.status === 1) {
						this.checkinData = res.data.data;
						// 计算打卡收入
						this.checkinSalary = this.checkinData.reduce((sum, item) => {
							return sum + parseFloat(this.calculateDailySalary(item));
						}, 0);
						this.calculateTotalSalary();
					}
				} catch (error) {
					console.error('获取打卡数据失败:', error);
				}
			},

			// 获取预约数据
			async getAppointmentData() {
				try {
					const res = await uni.request({
						url: `${globalVariable}/getAppointmentByTeacherId?teacherId=${this.teacherId}`
					});

					if (res.data.status === 1) {
						this.appointmentData = res.data.data;
						// 计算预约收入
						this.appointmentSalary = this.appointmentData.reduce((sum, item) => {
							return sum + parseFloat(item.money || 0);
						}, 0);
						this.calculateTotalSalary();
					}
				} catch (error) {
					console.error('获取预约数据失败:', error);
				}
			},

			// 计算总收入
			calculateTotalSalary() {
				this.totalSalary = this.checkinSalary + this.appointmentSalary;
			},

			// 初始化数据
			async initData() {
				const teacherId = await this.getTeacherId();
				if (teacherId) {
					await this.getCheckinData();
					await this.getAppointmentData();
				}
			}
		},
		onLoad() {
			this.initData();
		}
	}
</script>

<style>
	/* 引入animate.css动画库 */
	@import url('/static/animate.css');

	/* 基础样式 */
	.salary-container {
		min-height: 100vh;
		background-color: #ffffff;
		position: relative;
		padding-bottom: 120rpx;
		font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
	}

	/* 装饰元素 */
	.decoration-top {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 200rpx;
		overflow: hidden;
	}

	.circle {
		position: absolute;
		border-radius: 50%;
		opacity: 0.1;
	}

	.circle.pink {
		width: 300rpx;
		height: 300rpx;
		background-color: #FF9A9E;
		top: -150rpx;
		right: -50rpx;
	}

	.circle.blue {
		width: 200rpx;
		height: 200rpx;
		background-color: #6EC3F1;
		top: -80rpx;
		left: -50rpx;
	}

	.circle.yellow {
		width: 150rpx;
		height: 150rpx;
		background-color: #FFD166;
		top: 50rpx;
		left: 100rpx;
	}

	/* 主内容区域 */
	.content {
		padding: 30rpx;
		position: relative;
		z-index: 1;
	}

	/* 工资卡片 */
	.salary-card {
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
		border: 1rpx solid #f0f0f0;
	}

	.salary-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.month {
		font-size: 32rpx;
		color: #666;
		font-weight: 500;
	}

	.amount {
		font-size: 48rpx;
		font-weight: bold;
		color: #333;
		background: linear-gradient(to right, #6EC3F1, #5A7DFF);
		-webkit-background-clip: text;
		-webkit-text-fill-color: transparent;
	}

	/* 收入图表 */
	.income-chart {
		height: 80rpx;
		border-radius: 40rpx;
		background-color: #f5f7fa;
		overflow: hidden;
		display: flex;
		margin-top: 20rpx;
	}

	.chart-bar {
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		transition: width 0.8s ease;
	}

	.chart-bar.checkin {
		background: linear-gradient(to right, #6EC3F1, #5A7DFF);
	}

	.chart-bar.appointment {
		background: linear-gradient(to right, #FF9A9E, #FF6B95);
	}

	.chart-label {
		font-size: 26rpx;
		color: rgba(255, 255, 255, 0.9);
	}

	.chart-value {
		font-size: 28rpx;
		font-weight: bold;
		color: #fff;
	}

	/* 详情部分 */
	.detail-section {
		background-color: #ffffff;
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
		overflow: hidden;
		border: 1rpx solid #f0f0f0;
	}

	.section-header {
		display: flex;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.section-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 15rpx;
	}

	.section-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		flex: 1;
	}

	.section-total {
		font-size: 28rpx;
		font-weight: bold;
		color: #5A7DFF;
	}

	.detail-section.appointment .section-total {
		color: #FF6B95;
	}

	/* 打卡列表 */
	.checkin-list {
		padding: 0 30rpx;
	}

	.checkin-item {
		display: flex;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.checkin-item:last-child {
		border-bottom: none;
	}

	.date-badge {
		width: 150rpx;
		height: 150rpx;
		/* border-radius: 50%; */
		background-color: #E6F7FF;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
	}

	.day {
		font-size: 28rpx;
		font-weight: bold;
		color: #5A7DFF;
	}

	.week {
		font-size: 22rpx;
		color: #6EC3F1;
		margin-top: 5rpx;
	}

	.info {
		flex: 1;
	}

	.time {
		font-size: 28rpx;
		color: #333;
		display: block;
		margin-bottom: 8rpx;
	}

	.status-badge {
		display: inline-block;
		padding: 5rpx 15rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		background-color: #f0f0f0;
		color: #666;
	}

	.status-badge.completed {
		background-color: #E6FFED;
		color: #4CAF50;
	}

	.status-badge.partial {
		background-color: #FFF7E6;
		color: #FF9800;
	}

	.amount-badge {
		font-size: 28rpx;
		font-weight: bold;
		color: #5A7DFF;
		padding: 10rpx 15rpx;
		border-radius: 20rpx;
		background-color: #F0F7FF;
	}

	/* 预约列表 */
	.appointment-list {
		padding: 0 30rpx;
	}

	.appointment-item {
		display: flex;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.appointment-item:last-child {
		border-bottom: none;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 20rpx;
		border: 2rpx solid #f0f0f0;
	}

	.name {
		font-size: 28rpx;
		color: #333;
		display: block;
		margin-bottom: 5rpx;
	}

	.course {
		font-size: 24rpx;
		color: #666;
		display: block;
		margin-bottom: 5rpx;
	}

	.time {
		font-size: 24rpx;
		color: #999;
	}

	.detail-section.appointment .amount-badge {
		color: #FF6B95;
		background-color: #FFF0F5;
	}

	/* 底部统计 */
	.footer-stats {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		display: flex;
		padding: 25rpx 0;
		box-shadow: 0 -5rpx 20rpx rgba(0, 0, 0, 0.05);
		z-index: 10;
	}

	.stat-item {
		flex: 1;
		text-align: center;
	}

	.stat-value {
		font-size: 36rpx;
		font-weight: bold;
		color: #5A7DFF;
		display: block;
	}

	.stat-label {
		font-size: 24rpx;
		color: #666;
		display: block;
		margin-top: 5rpx;
	}

	.stat-divider {
		width: 1rpx;
		height: 50rpx;
		background-color: #f0f0f0;
		align-self: center;
	}

	/* 动画效果 */
	@keyframes fadeInUp {
		from {
			opacity: 0;
			transform: translateY(40rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	/* 交互效果 */
	.checkin-item:active,
	.appointment-item:active {
		background-color: #f9f9f9;
	}

	.salary-card:active {
		transform: translateY(5rpx);
	}
</style>